<?php

namespace api\zhuce\controller;

use api\zhuce\model\UserModel;
use api\zhuce\validate\UserValidate;
use cmf\controller\RestBaseController;

class UserController extends RestBaseController
{
    // 注册
    public function register(){
        // 接收数据
        $data = input('post.');

        // 查询账户是否已经注册
        $mobile = UserModel::where('mobile',$data['mobile'])->find();
        if($mobile){
            $this->error('手机号已被注册');
        }

        // 验证
        $validate = new UserValidate();
        $result = $validate->scene('register')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }

        // 验证验证码是否存在
        $check = checkSmsCode($data['mobile'], $data['code']);
        if(!$check){
            $this->error('验证码错误');
        }

       /* $randStr = createRandStr(8);
        $password = md5($data['password'].$randStr);*/
        /*$data['salt'] = $randStr;
        $data['password'] = $password;*/
        $data['create_time'] = time();
        $user = UserModel::create([
            'mobile' => $data['mobile']
        ]);

        // 判断是否成功
        if($user){
            $this->success('注册成功');
        }else{
            $this->error('注册失败');
        }
    }
    // 登录
    public function login(){
        // 接收数据
        $data = input('post.');
        $validate = new UserValidate();
        $result = $validate->scene('login')->check($data);
        if(!$result){
            return error($validate->getError());
        }

        //查询账号
        $user = UserModel::where('mobile', $data['mobile'])->find();

        //验证验证码是否存在
        $check = checkSmsCode($data['mobile'], $data['code']);
        if(!$check){
            $this->error('验证码错误');
        }
        if(!$user){
            $this->error('该账号不存在');
        }
        $this->success('登录成功');
    }

    // 发送验证码
    public  function  sendCode()
    {
        $data = input('post.');
        sendSms($data['mobile']);
    }
}
